package com.chinasoft.userservice.mapper;

import com.chinasoft.ms.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM user WHERE username = #{username}")
    User selectByName(String username);

    @Select("SELECT * FROM user WHERE id = #{id}")
    User selectById(Long id);

    @Select("<script>" +
            "SELECT * FROM user " +
            "<where>" +
            "   <if test='id != null'>AND id = #{id}</if>" +
            "   <if test='username != null and username != \"\"'>AND username LIKE CONCAT('%', #{username}, '%')</if>" +
            "   <if test='phone != null and phone != \"\"'>AND phone LIKE CONCAT('%', #{phone}, '%')</if>" +
            "   <if test='address != null and address != \"\"'>AND address LIKE CONCAT('%', #{address}, '%')</if>" +
            "</where>" +
            "</script>")
    List<User> selectByCondition(User query);

    @Insert("INSERT INTO user(username, password, role) " +
            "VALUES(#{username}, #{password}, #{role})")
    int insert(User user);

    @Update("<script>" +
            "UPDATE user " +
            "<set>" +
            "   <if test='username != null'>username = #{username},</if>" +
            "   <if test='password != null'>password = #{password},</if>" +
            "   <if test='nickName != null'>nick_name = #{nickName},</if>" +
            "   <if test='phone != null'>phone = #{phone},</if>" +
            "   <if test='sex != null'>sex = #{sex},</if>" +
            "   <if test='address != null'>address = #{address},</if>" +
            "   <if test='role != null'>role = #{role},</if>" +
            "</set> " +
            "WHERE id = #{id}" +
            "</script>")
    int update(User user);

    @Delete("DELETE FROM user WHERE id = #{id}")
    int deleteById(Long id);

    @Delete("<script>" +
            "DELETE FROM user WHERE id IN " +
            "<foreach collection='list' item='id' open='(' separator=',' close=')'>" +
            "   #{id}" +
            "</foreach>" +
            "</script>")
    int deleteBatch(List<Long> ids);

    @Select("SELECT role FROM user WHERE id = #{id}")
    Integer getUserRoleWithId(Long id);
}
